from pypdf import FPDF
import tempfile, os, re

class Separator(object):

  def __init__(self):
    self.__dotmatrixgenerator = None

  def set_dotmatrixgenerator(self, generator):
    self.__dotmatrixgenerator = generator

  def generate(self, box, section, output):
    tempimg = tempfile.NamedTemporaryFile(delete=False)

    separator_name = 'Box %d - Section %d' % (box, section)
    dotmatrix = self.__dotmatrixgenerator.generate(separator_name, tempimg.name)

    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page()
    pdf.set_font('Arial', 'B', 32)
    pdf.ln(80)
    pdf.cell(0, 30, 'Box %d - Section %d' % (box, section), 'B', 0, 'C') 
    pdf.image(tempimg.name, 80, 220, 40, 40, 'png')
    pdf.output(output, 'F')

    os.unlink(tempimg.name)

  def scan(self, input):
    text = self.__dotmatrixgenerator.parse(input)
    print text
    m = re.match("Box (\d+) - Section (\d+)", text)
    if m is None:
      raise Exception("DotMatrix scan failure: no location matched.")
    elif len(m.groups()) != 2:
      raise Exception("DotMatrix scan failure: bad location match: ", m.groups())
    else:
      return (int(m.group(1)), int(m.group(2)))


if __name__ == '__main__':
  from bettybox.DMTX import DMTX
  sep = Separator()
  sep.set_dotmatrixgenerator(DMTX())
  sep.generate(1, 5, 'output.pdf')
  location = sep.scan('output.pdf')
  print "%d - %d" % (location[0], location[1])



